package com.fenda.gallery

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import okhttp3.*
import java.io.IOException
import kotlin.coroutines.Continuation
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
import kotlin.math.ceil

const val DATA_STATUS_CAN_LOAD_MORE = 0
const val DATA_STATUS_NO_MORE = 1
const val DATA_STATUS_NETWORK_ERROR = 2
class GalleryViewModel(application: Application) : AndroidViewModel(application) {

    var needToScrollToTop = true

    private val _dataStatusLive = MutableLiveData<Int>()
    val dataStatusLive:LiveData<Int> get() = _dataStatusLive
    private val _photoListLive = MutableLiveData<List<PhotoItem>>()
    //获取到私有的数据列表
    val photoListLive: LiveData<List<PhotoItem>>
        get() = _photoListLive

    //随机
    private val keyWords = arrayOf("cat", "dog", "car", "beauty", "phone", "flower", "animal")

    /*  *
    * 首先给okhttp3.Call添加一个扩展函数，就是对okhttp3.Call的enqueue方法做了一个包装。
    * */
    @ExperimentalCoroutinesApi
    suspend fun okhttp3.Call.awaitResponse(): okhttp3.Response {
        return suspendCancellableCoroutine {

            it.invokeOnCancellation {
                //当协程被取消的时候，取消网络请求
                cancel()
            }

            enqueue(object : okhttp3.Callback {
                override fun onFailure(call: okhttp3.Call, e: IOException) {
                    isLoading = false
                    _dataStatusLive.value = DATA_STATUS_NETWORK_ERROR
                    it.resumeWithException(e)
                }

                override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) {
                    it.resume(response, null)
                }
            })
        }
    }

    private val perPage = 50
    private var currentPage = 1
    private var totalPage = 1
    private var currentKey = "cat"
    private var isNewQuery = true
    private var isLoading = false

    @ExperimentalCoroutinesApi
    suspend fun resetQuery() {
        currentPage = 1
        totalPage = 1
        currentKey = keyWords.random()
        isNewQuery = true
        //知会UI滚动到顶部
        needToScrollToTop = true
        fetchData()
    }

    @ExperimentalCoroutinesApi
    suspend fun fetchData() {
        if (isLoading) return
        if (currentPage > totalPage) {
            _dataStatusLive.value = DATA_STATUS_NO_MORE
            return
        }
        isLoading = true
        //创建一个request请求体
        val request = Request.Builder().url(getUrl()).get().build()
        //拿到http对象
        val call = OkhttpSingleton.getInstance(getApplication()).call
        //newCall并enqueue
        val awaitResponse = call.newCall(request).awaitResponse()
        val string = getString(awaitResponse)
        //Gson解析json并转成Pixabay对象
        with(Gson().fromJson(string, Pixabay::class.java)) {
            totalPage = ceil(totalHits.toDouble() / perPage).toInt()
            if (isNewQuery) _photoListLive.value = hits.toList()
            else _photoListLive.value = arrayListOf(_photoListLive.value!!, hits.toList()).flatten()
            _dataStatusLive.value = DATA_STATUS_CAN_LOAD_MORE
            isLoading = false
            isNewQuery = false
            currentPage++
        }
    }

    private fun getUrl(): String {
        return "https://pixabay.com/api/?key=22613441-de363051380effdc689d326e1&q=${currentKey}&per_page=${perPage}&page = ${currentPage}"
    }


    private suspend fun getString(response: Response): String {
        return withContext(Dispatchers.IO) {
            response.body?.string() ?: "empty string"
        }
    }
}

